#region Copyright RenGuiYou. All rights reserved.
//=====================================================
// NeatlyFrameWork
// Author:      RenGuiyou
// Feedback: 	mailto:750539605@qq.com
//=====================================================
#endregion
using System;
using System.IO;
using Cysharp.Threading.Tasks;
using Neatly.Load.Manager;
using UnityEngine;

namespace Neatly.Load
{
    public class AssetBundleLoader : Loader
    {
        protected override void Init(string path, bool sync = true)
        {
            IsAtlas = path.IndexOf(NeatlyConfig.PATH_BUNDLE_ATLAS_TP, StringComparison.Ordinal) != -1;
            if (IsAtlas)
            {
                AtlasName = path.Replace(NeatlyConfig.PATH_BUNDLE_ATLAS_TP, string.Empty).SubstringTo(".");
            }
            base.Init(path, sync);
        }

        protected override async UniTask<Loader> Load()
        {
            Developer.StartLoadBundle(Path);
            AssetBundle assetBundle = null;
#if UNITY_WEBGL
            var fileName = FileHashManager.Instance.GetFileName(NeatlyConfig.BUNDLE_PACKAGE, Path);
            var url = $"{NeatlyConfig.WEBGL_CDN_DOMAIN}/{fileName}";
            var request = NeatlyConfig.WebRequestAssetBundleAction(url);
            assetBundle = NeatlyConfig.DownloadGetAssetBundleAction((await request.SendWebRequest()).downloadHandler);
            request.Dispose();
#else
            string filePath = GetFilePath(Path);
            assetBundle = IsSync ? AssetBundle.LoadFromFile(filePath) : await AssetBundle.LoadFromFileAsync(filePath);
#endif
            Developer.EndLoadBundle(Path);
            if (IsAtlas)
            {
                Developer.StartLoadAtlas(Path);
                var gameObject = assetBundle.LoadAsset<GameObject>(AtlasName);
                AtlasInfo = gameObject.GetComponent<NAtlas>();
                AtlasInfo.Init();
                Developer.EndLoadAtlas(Path);
            }
            ResultObject = assetBundle;
            return this;
        }

        private string GetFilePath(string name)
        {
            name = FileHashManager.Instance.GetFileName(NeatlyConfig.BUNDLE_PACKAGE, name);
            foreach (var t in NeatlyConfig.ASSETS_PATHS)
            {
                var fullPath = $"{t}/{name}";
                if (File.Exists(fullPath))
                {
                    return fullPath;
                }
            }
            string inputPath = $"{NeatlyConfig.PATH_PACKAGE_BUNDLE}/{name}";
#if !UNITY_EDITOR && UNITY_ANDROID
            //找不到资源, 从包里copy
            string outputPath = $"{NeatlyConfig.PATH_UPDATE_BUNDLE}/{name}";
            Neatly.Module.FileModule.Instance.CopyFile(inputPath, outputPath);
            return outputPath;
#endif
            return inputPath;
        }
    }
}